package net.hashcoding.cookbook.io;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;

import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Created by Administrator on 2017/6/24.
 */
public class Database {

    private GenericObjectPool<Connection> pool;

    public Database() {
        pool = new GenericObjectPool<Connection>(new DatabaseFactory(new Config()));
    }

    public Connection borrowConnection() throws Exception {
        // NOTICE: this will block if pool is empty
        return pool.borrowObject();
    }

    public static class Config {
        private static final String URL = "jdbc:mysql://127.0.0.1/server";
        private static final String NAME = "com.mysql.jdbc.Driver";
        private static final String USERNAME = "root";
        private static final String PASSWORD = "root";

        public String getUrl() {
            return URL;
        }

        public String getName() {
            return NAME;
        }

        public String getUsername() {
            return USERNAME;
        }

        public String getPassword() {
            return PASSWORD;
        }
    }

    public static class Connection {
        private java.sql.Connection connection;

        public Connection(java.sql.Connection connection) {
            this.connection = connection;
        }


    }


    private static class DatabaseFactory extends BasePooledObjectFactory<Connection> {

        private final Config config;

        DatabaseFactory(Config config) {
            this.config = config;
            try {
                Class.forName(config.getName());
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

        public Connection create() {
            try {
                java.sql.Connection connection = DriverManager.getConnection(config.getUrl(),
                        config.getUsername(), config.getPassword());
                return new Connection(connection);
            } catch (SQLException e) {
                e.printStackTrace();
                return null;
            }
        }

        public PooledObject<Connection> wrap(Connection connection) {
            return new DefaultPooledObject<Connection>(connection);
        }
    }

}
